<?php

namespace app\enterprise\controller;

use app\enterprise\model\train\Train as TrainModel;
use app\enterprise\model\staff\Staff;
use think\exception\ValidateException;


class Train extends Enterprise
{

    public function list()
    {
        $page = input('page', 1);
        $size = input('size', 10);
        $training_name = input('train_name', '');
        $submit_status = input('submit_status', '');
        $start_time = strtotime(input('start_time', ''));
        $end_time = strtotime(input('end_time', ''));

        $data = TrainModel::where('status', 1)
            ->where('company_id', $this->adminId)
            ->when($training_name, function ($query) use ($training_name) {
                $query->where('train_name', 'like', '%' . $training_name . '%');
            })
            ->when($submit_status, function ($query) use ($submit_status) {
                $query->where('submit_status', $submit_status);
            })
            ->when($start_time, function ($query) use ($start_time) {
                $query->where('time', '>=', $start_time);
            })
            ->when($end_time, function ($query) use ($end_time) {
                $query->where('time', '<=', $end_time);
            })
            ->with('user')
            ->order('id', 'desc')
            ->paginate($size)
            ->each(function ($item) {
                $item->time = date('Y-m-d H:i:s', $item->time);
                $staff = Staff::getOne($item->appoint_staff_id);
                if ($staff) {
                    $item->appoint_staff_name = $staff->username;
                } else{
                    $item->appoint_staff_name = '';
                }
                if ($item->inner_staff_ids) {
                    $item->inner_staff_names = Staff::where('id', 'in', explode(',', $item->inner_staff_ids))->column('username');
                } else {
                    $item->inner_staff_names = [];
                }
                if ($item->img_urls) {
                    $item->img_urls = explode(',', $item->img_urls);
                } else {
                    $item->img_urls = [];
                }

                if ($item->video_urls) {
                    $item->video_urls = explode(',', $item->video_urls);
                } else {
                    $item->video_urls = [];
                }

                if (!empty($item->user)) {
                    $item->company_name = $item->user->company_name;
                    unset($item->user);
                } else {
                    $item->company_name = '未知';
                }

            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
            'total_page'=>$data->lastPage(),
        ]);
    }

    public function save()
    {
        $data = $this->request->only([
            'appoint_staff_id', 'train_name', 'time', 'content', 'address', 'staff_names',
            'teacher', 'staff_ids', 'remark'
        ]);

        try {
            validate([
                'train_name|培训名称' => 'require|max:255',
                'time|培训时间' => 'require|dateFormat:Y-m-d H:i:s',
//                'img_url|培训图片' => 'require|max:255',
                'address|培训地点' => 'require|max:255',
                'content|培训内容' => 'require|max:255',
                'appoint_staff_id|培训组织人' => 'require|number',
//                'submit_status|提交状态' => 'require|number|in:1,2',
                'teacher|授课老师' => 'require|max:255',
                'staff_names|其他参与人员' => 'max:255',
                'remark|备注' => 'max:255',
                'staff_ids|内部人员' => 'array',
            ])->check($data);

            // 数组转为英文逗号分隔
            $data['inner_staff_ids'] = implode(',', input('inner_staff_ids', []));
//            $data['staff_names'] = implode(',', input('staff_names', []));

            $data['company_id'] = $this->adminId;

            $id = input('id', '');

            $data['time'] = strtotime($data['time']);
            if (!$id) {
                // 新增
                $data['creator_id'] = $this->adminId; // 创建人
                $res = TrainModel::create($data);
                $id = $res->id;
            } else {

                $model = TrainModel::getOne($id);
                if (!$model) {
                    return app('json')->fail('数据不存在');
                }
                if ($model->submit_status == 2) {
                    return app('json')->fail('已提交，不能修改');
                }
                if ($model->company_id != $this->adminId) {
                    return app('json')->fail('无权操作此数据');
                }

                TrainModel::update($data, ['id' => $id]);
            }
            return app('json')->success('保存成功');
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
    }

    public function info()
    {
        $id = input('id', '');

        $model = TrainModel::getOne($id);
        if (!$model) {
            return app('json')->fail('数据不存在');
        }

        if ($model->img_urls) {
            $model->img_urls = explode(',', $model->img_urls);
        } else{
            $model->img_urls = [];
        }

        if ($model->video_urls) {
            $model->video_urls = explode(',', $model->video_urls);
        } else{
            $model->video_urls = [];
        }

        $model->time = date('Y-m-d H:i:s', $model->time);
        $staff = Staff::getOne($model->appoint_staff_id);
        if (!empty($staff)) {
            $model->appoint_staff_name = $staff->username;
        } else {
            $model->appoint_staff_name = '';
        }


        $model->inner_staff_ids = explode(',', $model->inner_staff_ids);


        if ($model->inner_staff_ids) {
            $model->inner_staff_names = Staff::where('id', 'in', $model->staff_ids)->column('username');
        } else {
            $model->inner_staff_names = [];
        }

        return app('json')->success([
            'model' => $model
        ]);

    }


    public function delete()
    {
        $id = input('id', '');
        $model = TrainModel::getOne($id);
        if (!$model) {
            return app('json')->fail('数据不存在');
        }
        if ($model->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }
        TrainModel::dataDelete($id);
        return app('json')->success('删除成功');
    }


}